package com.itheima.demo07;

public class SearchDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int num = 11;

        long start = System.currentTimeMillis();
        int index = indexSearch(arr, num);
        System.out.println(index);
        long end = System.currentTimeMillis();
        System.out.println("方法运行了" + (end - start) + "毫秒");
    }

    //二分查找方法
    private static int indexSearch(int[] arr, int num) {
        int min = 0;
        int max = arr.length - 1;

        while (min <= max) {
            int mid = (min + max) >> 1;

            //判断中间索引元素是否大于num，大于的话去掉左边，让min = mid + 1，小于的话让max = mid - 1，进行下一次的查找
            if (arr[mid] < num) {
                min = mid + 1;
            } else if (arr[mid] > num) {
                max = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }
}
